<template>
  <div
    class="followGoods"
    id="pdfDom">
    <el-container
      class="followGoods-box"
    >
      <el-header>
        <h3 style="text-align: center;">随货同行单</h3>
        <h3 style="text-align: center;">{{ info.peerListName }}</h3>
        <h5 style="text-align: center;">{{ info.deliveryDate }}</h5>
      </el-header>
      <div class="followGoods-baseifo">
        <div class="followGoods-baseifo-left">
          <div
            v-for="(item, index) in formColumns"
            :key="index">
            <span class="left-span">{{ item.label }}:
            </span>
            <span class="right-span">{{ info[item.value] }}
            </span>
          </div>
        </div>
        <div class="followGoods-baseifo-right">
          <img
            v-show="qrcodeImg"
            :src="qrcodeImg"
            alt="编号">
          <div>医疗机构可在“扫码收货”处进行扫描</div>
        </div>
      </div>
      <el-editable
        class="hospital-edit-box"
        :data="list"
        v-loading="tableLoading"
        :columns="activeListColumns"
      >
        <template
          slot="default-certNo"
          slot-scope="scope">
          <div>
            <cell-registration
              :key="scope.row.certNo"
              :regis-no="scope.row.certNo"
              :content="'注册证已过期，点击查看详细信息'"
              :status="scope.row.isNoExpire"
              :regis-data="scope.row.registrationInfo"
            />
          </div>
        </template>
      </el-editable>
      <div class="followGoods-baseifo followGoods-price">
        <div>
          <span class="left-span">
            总计金额:
          </span>
          <span>
            {{ info.totalAmount }}
          </span>
        </div>
        <div>
          <span class="left-span">
            大写金额:
          </span>
          <span>
            {{ info.amountInWords }}
          </span>
        </div>
      </div>
      <div class="foot">
        <span
          v-for="(item, index) in infoColumns"
          :key="index">
          <span class="left-span">{{ item.label }}:
          </span>
          <span>
            {{ info[item.value] }}
          </span>
        </span>
      </div>
      <div class="foot">
        <span
          v-for="(item, index) in footColumns"
          :key="index">
          <span class="left-span">{{ item.label }}:
          </span>
          <span>
            {{ item.value }}
          </span>
        </span>
      </div>
    </el-container>
  </div>
</template>

<script>
import QRCode from 'qrcode'
import { afterListColumns, beforeListColumns, formColumns, infoColumns, footColumns } from './const'
import { _print } from '@const/print'
import ElEditable from '@components/el-editable'
import { getFormatterPrice } from '@const/filter'
import CellRegistration from '@/moduleComponents/common/detail/cell-registration'
import {
  wscSaleOrderGetPeer, // 获取指定的随货同行单信息（结算前）
  saleManagerGetPeer, // 获取指定的随货同行单信息（后结算)
  updatePrintCountBefore, // 更新随货同行单打印次数（结算前）
  updatePrintCountAfter // 更新随货同行单打印次数（后结算)
} from '@const/beforeSettleApi'
export default {
  components: { ElEditable, CellRegistration },
  data () {
    return {
      tableLoading: false,
      htmlTitle: '随货同行单',
      list: [],
      qrcodeImg: null,
      formColumns,
      infoColumns,
      footColumns,
      info: {},
      printContent: ''
    }
  },
  computed: {
    // roleType   登录角色（1-医院 2-配送商）
    roleType () {
      return Number(this.$route.query.roleType)
    },
    // settle    1-结算前，2-结算后
    settle () {
      return Number(this.$route.query.settle)
    },
    id () {
      return this.$route.query.id
    },
    activeListColumns () {
      if (this.settle === 1) {
        return beforeListColumns
      }
      if (this.settle === 2) {
        return afterListColumns
      }
    }
  },
  mounted () {
    let arr = [
      { type: 'primary', val: '打印', handle: this.print },
      { type: 'primary', val: '下载', handle: this.downloadToPdf }
    ]
    const btn = {
      type: 'btn',
      arr: arr
    }
    this.$store.commit('changeLayoutHandle', btn)
    this.getList()
  },
  methods: {
    // 获取打印内容和prd内容
    getPrintContent () {
      let content = `<div style="margin: 0; padding-top: 20px; box-sizing: border-box; height: auto"> 
        <h3 style="text-align: center; margin: 0;">随货同行单</h3>
        <h3 style="text-align: center; margin: 0;">${this.info.peerListName || ''}</h3>
        <h5 style="text-align: center; margin: 0;">${this.info.deliveryDate || ''}</h5>
        <div style="text-align: center;
          display: flex;
          justify-content: space-between;
          margin-bottom: 20px;">
        <div style="display: flex;
          justify-content: space-around;
          flex-direction: column;">
          ${this.formColumns.map(item => {
    return `
              <div style="min-width: 300px;
                max-width:600px;
                text-align: left;">
                <span style="color: #111;
                  display: inline-block;
                  width: 80px;
                  text-align: right;">
                  ${item.label}:
                </span>
                <span>
                  ${this.info[item.value] || ''}
                </span>
              </div>`
  }).join('')}
        </div>
        <div>
          <img
            src="${this.qrcodeImg}"
            alt="编号"/>
          <div>医疗机构可在“扫码收货”处进行扫描</div>
        </div>
      </div>
        <table width="100%" border="1" cellpadding="0" cellspacing="0" style="margin: 0;"  > 
          ${this._ListStr()}
        </table> 
        <div style="text-align: center;
          display: flex;
          justify-content: space-between;
          padding: 5px 0;
          margin: -1px 0 0 0;
          border: 1px solid #333;
          background: #EBEEF5;">
          <div>
            <span style="color: #111;
              display: inline-block;
              width: 80px;
              text-align: right;">
              总计金额:
            </span>
            <span>
              ${this.info.totalAmount}
            </span>
          </div>
          <div style="padding-right: 20px;">
            <span span style="color: #111;
              display: inline-block;
              width: 80px;
              text-align: right;">
              大写金额:
            </span>
            <span>
              ${this.info.amountInWords}
            </span>
          </div>
        </div>
        <div style="margin-top: 10px;">
          ${this.infoColumns.map(item => {
    return `
              <span style="min-width: 150px; display: inline-block;">
                <span style="color: #111;">${item.label}:
                </span>
                <span>
                  ${this.info[item.value] || ''}
                </span>
              </span>
            `
  }).join('')}
        </div>
        <div style="margin-top: 10px;">
          ${this.footColumns.map(item => {
    return `
              <span style="display: inline-block;">
                <span style="color: #111;">${item.label}:
                </span>
                <span>
                  ${item.value}
                </span>
              </span>
            `
  }).join('')}
        </div>
      </div>` // 获取需要打印的页面元素 ，page1元素设置样式page-break-after:always，意思是从下一行开始分割。
      return content
    },
    // 结算前详情
    async getBeforeList () {
      const requestData = {
        deliveryOrderId: this.id
      }
      const responsedata = await this.$axios.$post(wscSaleOrderGetPeer, requestData)
      const { productItemList, ...info } = responsedata.payload
      this.list = productItemList
      this.info = info
      this.getCode(this.info.deliveryCode)
    },
    // 后结算详情
    async getAfterList () {
      const requestData = {
        deliveryOrderId: this.id
      }
      const responsedata = await this.$axios.$post(saleManagerGetPeer, requestData)
      const { productItemList, ...info } = responsedata.payload
      // for (let i = 0; i < 100; i++) {
      //   this.list.push(...productItemList)
      // }
      this.list = productItemList
      this.info = info
      this.getCode(this.info.deliveryCode)
    },
    async getList (type = this.settle) {
      if (type === 1) {
        await this.getBeforeList()
      }
      if (type === 2) {
        await this.getAfterList()
      }
      // 打印内容以及prd内容
      this.printContent = this.getPrintContent()
    },
    // 生成二位码
    getCode (str = '12345') {
      QRCode.toDataURL(str)
        .then(url => {
          this.qrcodeImg = url
        })
        .catch(() => {
          this.$message({ type: 'error', message: '生成二维码失败，建议使用本地上传！' })
        })
    },
    // 更新打印次数--后结算
    async updatePrintBefore () {
      const requestData = {
        deliveryOrderId: this.id,
        roleType: this.roleType
      }
      try {
        const data = this.$axios.$post(updatePrintCountBefore, requestData)
      } catch (error) {
        this.$message.warning('出错了')
      }
    },
    // 更新打印次数--后结算
    updatePrintAfter () {
      const requestData = {
        deliveryOrderId: this.id,
        roleType: this.roleType
      }
      try {
        const data = this.$axios.$post(updatePrintCountAfter, requestData)
      } catch (error) {
        this.$message.warning('出错了')
      }
    },
    _ListStr (data = this.list) {
      // bug:在生成pdf是类似'a-b-c-d-'被认为是一个整体不换行  需要强制换行word-break:break-all; word-wrap:break-word;
      let str = `
        <tr style="background: #EBEEF5;">
          ${this.activeListColumns.map(item => {
    return `<th style="font-size: 16px; text-align: center; min-width: 80px;">${item.label}</th>`
  }).join('')}
        </tr>
      `
      data.forEach((item, index) => {
        str += `
          <tr>
            ${this.activeListColumns.map(col => {
    const content = ['prodPrice', 'prodAmount'].includes(col.prop) ? getFormatterPrice(item[col.prop]) : (item[col.prop] || '')
    return `<td style="padding: 3px 0; font-size: 16px; text-align: center; word-break:break-all; word-wrap:break-word;">${content}</td>`
  }).join('')}
          </tr>
        `
      })
      return str
    },
    // 打印附加--打印次数更新
    print (type = this.settle) {
      // 打印弹窗
      if (type === 1) {
        this.updatePrintBefore()
      }
      if (type === 2) {
        this.updatePrintAfter()
      }
      _print(this.printContent, [], '0.7')
    },
    // 下载
    downloadToPdf () {
      this.getPdf(this.printContent, this.htmlTitle, '1.2')
    }
  }
}
</script>

<style lang="less">
.followGoods {
  .followGoods-box {
    padding: 20px;
  }
  .followGoods-baseifo {
    text-align: center;
    display: flex;
    justify-content: space-between;
    .followGoods-baseifo-left {
      display: flex;
      justify-content: space-around;
      flex-direction: column;
    }
    .followGoods-baseifo-left > div {
      text-align: left;
    }
  }
  .foot {
    padding: 5px 0;
    text-align: left;
    & > span {
      min-width: 120px;
      display: inline-block;
      padding: 0 20px 0 0;
    }
  }
  .left-span {
    color: #666;
    display: inline-block;
    width: 60px;
    text-align: right;
  }
  .right-span {
    display: inline-block;
    width: 600px;
    text-align: left;
  }
  .followGoods-price {
    padding: 5px 0;
    background: #ebeef5;
    & > div:nth-last-child(1) {
      padding-right: 100px;
    }
  }
}

</style>
